/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbquestion_client.form;

import bllobjects.Account;
import chat.ChatMessage;
import chat.TextChatMessage;
import chat.sound.SoundFocusListener;
import fsktms.request.IRequestDelegate;
import fsktms.request.Request;
import fsktms.request.RequestParameters;
import fsktms.request.RequestRespond;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.text.DefaultCaret;
import model.ClientModel;
import model.FriendListModel;
import model.chat.ChatMessageModel;
import qclient.QClient;

/**
 *
 * @author Mrkupi
 */
public class roomChat extends javax.swing.JFrame implements ListDataListener, SoundFocusListener
{
    private String roomID;
    private String roomName;
    private ChatMessageModel messageModel;
    //======================

    /**
     * Creates new form roomChat
     */
    public roomChat(String roomID, String roomName)
    {
        initComponents();

        this.roomName   =   roomName;

        // HARD CODED
        setLocation(400, 200);
        this.roomID = roomID;
        
        initWindowCustomize();
        joinRoom();
        loadUserInfo();
        loadRoomMember();
        
        loadRoomHistory();
    }

    @Override
    public void dispose(){
        this.leaveRoom();
        if (roomID.equals(ClientModel.getInstance().getSoundChatManager().getFocusID()))
        {
            ClientModel.getInstance().getSoundChatManager().setFocusID(null, false);
        }
        ClientModel.getInstance().getSoundChatManager().getListeners().remove(this);
        if (this.messageModel != null)
        {
            this.messageModel.removeListDataListener(this);
        }
        super.dispose();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblRoomName = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taChatBox = new javax.swing.JTextArea();
        tfChat = new javax.swing.JTextField();
        btEnter = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblLevel = new javax.swing.JLabel();
        lblExp = new javax.swing.JLabel();
        lblNickName = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        btnPostQuestion = new javax.swing.JButton();
        btnAttachFile = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        roomMembers = new javax.swing.JList();
        btnSound = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblRoomName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblRoomName.setText("ROOM NAME");

        taChatBox.setEditable(false);
        taChatBox.setColumns(20);
        taChatBox.setLineWrap(true);
        taChatBox.setRows(5);
        taChatBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                taChatBoxMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(taChatBox);

        tfChat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                onEnter_pressed(evt);
            }
        });

        btEnter.setText("Enter");
        btEnter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onEnter_clicked(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Level");

        jLabel3.setText("Exp");

        jLabel4.setText("Nick name");

        lblLevel.setText("jLabel5");

        lblExp.setText("jLabel6");

        lblNickName.setText("Cuoi Say Ngat Ngay");

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/popo_emotions_full_version boss copy.png"))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblLevel)
                            .addComponent(lblExp)
                            .addComponent(lblNickName)))
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lblLevel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblExp))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblNickName))
                .addContainerGap())
        );

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("ROOMATES");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnPostQuestion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPostQuestionActionPerformed(evt);
            }
        });

        btnAttachFile.setText("Attach File");
        btnAttachFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAttachFileActionPerformed(evt);
            }
        });

        roomMembers.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(roomMembers);

        btnSound.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/voice-support copy.png"))); // NOI18N
        btnSound.setText("Sound: Deactivated");
        btnSound.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSoundActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 2, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnPostQuestion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnAttachFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnSound, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(tfChat, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btEnter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                            .addComponent(jScrollPane2)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(322, 322, 322)
                        .addComponent(lblRoomName)))
                .addGap(22, 22, 22))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(lblRoomName)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(btnPostQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAttachFile)
                        .addGap(18, 18, 18)
                        .addComponent(btnSound, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane2))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tfChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btEnter))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void onEnter_pressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_onEnter_pressed
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {                                
            this.sendMessageToAllPeople();
        }
    }//GEN-LAST:event_onEnter_pressed

    private void onEnter_clicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onEnter_clicked
        this.sendMessageToAllPeople();
    }//GEN-LAST:event_onEnter_clicked

//=============================================================
    private void btnPostQuestionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPostQuestionActionPerformed

    }//GEN-LAST:event_btnPostQuestionActionPerformed

    private void btnAttachFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAttachFileActionPerformed
//        JFileChooser fileChooser = new JFileChooser();
//        fileChooser.showOpenDialog(this);
//        
//        File fileChosen = fileChooser.getSelectedFile();
//        if( fileChosen != null )
//        {
//            try {
//                FileInputStream fis = new FileInputStream(fileChosen);
//                byte[] contents = new byte[(int)fileChosen.length()];
//                fis.read(contents);
//
//                // Create file message
//                FileMessage fm = null;
//                fm = FileMessage.createMessage(ClientModel.getInstance().getAccount().getUserID(), 
//                                                fileChosen.getName(), contents, roomID);
//                SBLLFactory.getInstance().getServerChat().postFile( fileChosen.getName(), fm );
//
//                fis.close();
//
//            } catch (FileNotFoundException | RemoteException ex) {
//                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
//            } catch (IOException ex) {
//                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
//            }
//        }
    }//GEN-LAST:event_btnAttachFileActionPerformed

    private void taChatBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_taChatBoxMouseClicked
        
//        int currentPos = taChatbox.getCaretPosition();
//        int counter = 0;
//        for (String line : taChatbox.getText().split("\\n")) 
//        {
//            counter += line.length() + 1;
//            if(counter >= currentPos && line.contains(" - Download "))
//            {
//                String fileName = line.replace(" - Download ", "");
//                String[] arr = fileName.split(": ");
//                try {
//                    downloadFile(arr[1]);
//                } catch (RemoteException ex) {
//                    Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
//                } catch (IOException ex) {
//                    Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        }
    }//GEN-LAST:event_taChatBoxMouseClicked

    private void btnSoundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSoundActionPerformed
        if (roomID.equals(ClientModel.getInstance().getSoundChatManager().getFocusID()))
        {
            ClientModel.getInstance().getSoundChatManager().setFocusID(null, false);
        }
        else
        {
            ClientModel.getInstance().getSoundChatManager().setFocusID(roomID, false);
        }
    }//GEN-LAST:event_btnSoundActionPerformed

//=============================================================

    private boolean makeSureNotEmptyTextField() {
        // NEED TABLE
        if ("".equals(tfChat.getText())) {
            JOptionPane.showMessageDialog(this, "Empty message");
            return false;
        }

        return true;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btEnter;
    private javax.swing.JButton btnAttachFile;
    private javax.swing.JButton btnPostQuestion;
    private javax.swing.JButton btnSound;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblExp;
    private javax.swing.JLabel lblLevel;
    private javax.swing.JLabel lblNickName;
    private javax.swing.JLabel lblRoomName;
    private javax.swing.JList roomMembers;
    private javax.swing.JTextArea taChatBox;
    private javax.swing.JTextField tfChat;
    // End of variables declaration//GEN-END:variables
    // Extends attribute

    private void initWindowCustomize() {
        taChatBox.setWrapStyleWord(true);
        DefaultCaret dc = (DefaultCaret) taChatBox.getCaret();
        dc.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        
        roomMembers.setBorder(BorderFactory.createLineBorder(Color.black));
        roomMembers.addMouseListener(new MouseAdapter() { 
            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    Account selectedFriend = (Account) roomMembers.getSelectedValue();
                    if (selectedFriend != null && !selectedFriend.getUserID().equals(
                            ClientModel.getInstance().getAccount().getUserID()))
                    {
                        ClientModel.getInstance().getForms().showChatForm(selectedFriend, ClientForms.CHATFORM_PRIVATE);
                    }
                }
            }
        });
        roomMembers.addMouseListener(dc);
    }
    
    private void loadRoomHistory()
    {
        try
        {
        System.out.println("Begin load history message");
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "getHistoryMessage")
                    .set("ReceiverID", this.roomID);
            final roomChat copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(new Request(
                    "Chat", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                        ArrayList<TextChatMessage> messages = (ArrayList<TextChatMessage>) respond.getResult();
                        messageModel = new ChatMessageModel(messages);
                        messageModel.addListDataListener(copyThis);
                        ClientModel.getInstance().getMessageModels().put(roomID, messageModel);
                        copyThis.reloadAllMessages();
                        System.out.println("End load history messages");
                    }
                }
            }));
        } catch (IOException ex) {
            Logger.getLogger(worldChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void loadUserInfo() {
        this.lblNickName.setText(ClientModel.getInstance().getAccount().getUserName());
        this.lblExp.setText(String.valueOf(ClientModel.getInstance().getAccount().getExp()));
        this.lblLevel.setText(String.valueOf(ClientModel.getInstance().getAccount().getLevel()));
        this.lblRoomName.setText(this.roomName);
    }

    private void joinRoom()
    {
        ClientModel.getInstance().getSoundChatManager().getListeners().add(this);
        try
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "joinRoom")
                    .set("RoomID", this.roomID)
                    .set("UserID", ClientModel.getInstance().getAccount().getUserID());
            final roomChat copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(new Request(
                    "Chat", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                    }
                }
            }));
        } catch (IOException ex) {
            Logger.getLogger(worldChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void leaveRoom()
    {
        try
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "leaveRoom")
                    .set("RoomID", this.roomID)
                    .set("UserID", ClientModel.getInstance().getAccount().getUserID());
            final roomChat copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(new Request(
                    "Chat", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                    }
                }
            }));
        } catch (IOException ex) {
            Logger.getLogger(worldChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void loadRoomMember() {
        FriendListModel frListModel = ClientModel.getInstance().getRoomUsers().get(this.roomID);
        if (frListModel != null)
        {
            this.roomMembers.setModel(frListModel);
            return;
        }
        try
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "getRoomUsers")
                    .set("RoomID", this.roomID);
            final roomChat copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(new Request(
                    "Chat", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                        ArrayList<Account> users = (ArrayList<Account>) respond.getResult();
                        FriendListModel frListModel = new FriendListModel();
                        frListModel.addAccounts(users);
                        copyThis.roomMembers.setModel(frListModel);
                        ClientModel.getInstance().getRoomUsers().put(roomID, frListModel);
                    }
                }
            }));
        } catch (IOException ex) {
            Logger.getLogger(worldChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    @Override
    public void intervalAdded(ListDataEvent e) {
        for (int i = e.getIndex0(); i < e.getIndex1(); ++i)
        {
            TextChatMessage chatMsg = (TextChatMessage) messageModel.getElementAt(i);
            this.appendMessage(chatMsg);
        }
    }

    @Override
    public void intervalRemoved(ListDataEvent e) {
        this.reloadAllMessages();
    }

    @Override
    public void contentsChanged(ListDataEvent e) {
        this.reloadAllMessages();
    }
    
    private void appendMessage(TextChatMessage chatMsg)
    {
        this.taChatBox.append(chatMsg + "\n");
        System.out.println("Append message " + chatMsg);
    }
    
    private void reloadAllMessages()
    {
        System.out.println("Reload all messages, nMessage " + messageModel.getSize());
        this.taChatBox.setText(null);
        for (int i = 0; i < messageModel.getSize(); ++i)
        {
            TextChatMessage chatMsg = (TextChatMessage) messageModel.getElementAt(i);
            this.appendMessage(chatMsg);
        }
        System.out.println("Reload all messages completed");
    }
    
    private boolean sendMessageToAllPeople()
    {
        if( !makeSureNotEmptyTextField() )
            return false;
        try
        {
            String msgContent = this.tfChat.getText();
            this.tfChat.setText(null);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            TextChatMessage chatMsg = new TextChatMessage(
                    ClientModel.getInstance().getAccount().getUserID(),
                    roomID,
                    msgContent);
            oos.writeObject(chatMsg);
            QClient.getInstance().getNetClient().sendMessage(bos.toByteArray(), 
                    ChatMessage.CHAT_MESSAGE_MAGICKEY);
            this.messageModel.addMessage(chatMsg);
        }
        catch (IOException ex)
        {
            
        }
        
        return false;
    }    

    @Override
    public void onFocusChanged(String focus, String oldFocus)
    {
        if (roomID.equals(focus))   // has focus
        {
            this.btnSound.setText("Sound: Listen");
            this.sendListen();
        }
        else    // no focus
        {
            if (roomID.equals(oldFocus))    // lost focus
            {
                this.sendMute();
            }
            
            this.btnSound.setText("Sound: Muted");
        }
    }

    @Override
    public void becomeTalker(String talkerID) {
        this.btnSound.setText("Sound: Talk");
        ClientModel.getInstance().getSoundChatManager().startRecord();
    }
    
    private void sendListen()
    {
        try
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "listenRoom")
                    .set("RoomID", this.roomID)
                    .set("UserID", ClientModel.getInstance().getAccount().getUserID());
            final roomChat copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(new Request(
                    "Chat", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                    }
                }
            }));
        } catch (IOException ex) {
            Logger.getLogger(worldChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void sendMute()
    {
        try
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "muteRoom")
                    .set("RoomID", this.roomID)
                    .set("UserID", ClientModel.getInstance().getAccount().getUserID());
            final roomChat copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(new Request(
                    "Chat", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                    }
                }
            }));
        } catch (IOException ex) {
            Logger.getLogger(worldChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
